﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;

namespace ComTools
{
	public partial class frmControllerBasic : Form
	{
		public frmControllerBasic()
		{
			InitializeComponent();
		}

		private void frmLocation_Load(object sender, EventArgs e)
		{
			Reload();
		}

		private void Reload()
		{
			OutputLine("Hello");
			OutputLine("World");
		}

		#region 输出
		private void AppendText(string txt)
		{
			if (textBox1.Lines.Length > 100)
			{
				textBox1.Clear();
			}
			this.textBox1.AppendText(txt);
		}

		Action<string> HandlerSetText = null;

		private void Output(string msg)
		{
			if (HandlerSetText == null)
			{
				HandlerSetText = new Action<string>(AppendText);
			}
			if (this.InvokeRequired)
			{
				this.Invoke(HandlerSetText, msg);
			}
			else
			{
				AppendText(msg);
			}
		}

		private void OutputLine(string msg)
		{
			Output(msg + Environment.NewLine);
		}
		#endregion

		private void btnEventTest_Click(object sender, EventArgs e)
		{
			Publisher publisher = new Publisher();
			publisher.StateChange += ((x) => {
				OutputLine(x.ToString());
			});
			//
			for (int i = 0; i < 10; i++)
			{
				new System.Threading.Thread(new System.Threading.ThreadStart(() =>
				{
					publisher.Status = i;
				})).Start();
			}
		}

	}

	class Publisher
	{

		int _Status = 0;
		public int Status
		{
			get { return _Status; }
			set
			{
				if (value != _Status)
				{
					int tmp = _Status;
					_Status = value;
					if (StateChange != null)
					{
						StateChange(new MyEventArgs() { OldState = tmp, NewState = value });
					}
				}
			}
		}

		public delegate void MyHandler(MyEventArgs e);

		public event MyHandler StateChange;
	}

	class MyEventArgs : EventArgs
	{
		public int OldState { get; set; }
		public int NewState { get; set; }

		public override string ToString()
		{
			return $"OldState:{OldState} -> NewState:{NewState}";
		}
	}
}